package com.apkcore.core.ui.toolbar

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.LinearLayout
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentContainerView
import com.apkcore.core.databinding.TitleBarLayoutBinding
import com.apkcore.core.ext.addColorMask
import com.apkcore.core.ext.addRippleEffect
import com.apkcore.core.ext.brightness
import com.apkcore.core.ext.dp2px
import com.apkcore.core.ext.getCurrentActivity
import com.apkcore.core.ext.getSystemWindow
import com.apkcore.core.ext.nav
import com.apkcore.core.ext.setLightStatusBars


class TitleBar : LinearLayout {

    private lateinit var binding: TitleBarLayoutBinding
    private val getActionBarSize by lazy {
        44.dp2px()
//        return context.getActionBarSize()
    }

    constructor(context: Context) : super(context) {
        initTitleBar(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initTitleBar(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initTitleBar(context)
    }

    private fun initTitleBar(context: Context) {
        binding = TitleBarLayoutBinding.inflate(LayoutInflater.from(context), null, false)
//        val inflate = LayoutInflater.from(context).inflate(R.layout.title_bar_layout, null, false)
        addView(binding.root)

        binding.linear.setLayoutParams(
            LinearLayoutCompat.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                getActionBarSize
            )
        )

        binding.linear.getSystemWindow { systemWindow ->
            //为需要偏移的view设置padding
            binding.linear.setPadding(0, systemWindow.top, 0, 0)
            binding.linear.setLayoutParams(
                LinearLayoutCompat.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    getActionBarSize + systemWindow.top
                )
            )
        }

        viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                if (isInFragment()) {
                    setOnBackClickListener { nav().popBackStack() }
                } else {
                    setOnBackClickListener { (context as? Activity)?.finish() }
                }
                // 移除监听器以避免重复调用
                viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })

    }

    private fun getNumberOfActivities(context: Context): Int {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningTaskInfoList = activityManager.getRunningTasks(1)
        return if (runningTaskInfoList.isNotEmpty()) {
            runningTaskInfoList[0].numActivities
        } else {
            0
        }
    }

    private fun isInFragment(): Boolean {
        var p = parent
        while (p is View) {
            if (p is FragmentContainerView) {
                return true
            }
            p = (p as? View)?.parent
        }
        return false
    }

    fun setOnBackClickListener(l: OnClickListener): TitleBar {
        binding.layoutBack.addColorMask()
        binding.layoutBack.setOnClickListener(l)
        return this
    }

    /**
     * 描述：设置标题文本.
     *
     * @param text 文本
     */
    fun setTitleText(text: String): TitleBar {
        binding.titleView.text = text
        return this
    }

    private var lightColor = ContextCompat.getColor(context, android.R.color.white)
    private var darkColor = ContextCompat.getColor(context, android.R.color.black)
    private var currColor = ContextCompat.getColor(context, android.R.color.white)

    fun setBrightnessColor(
        lightColor: Int = ContextCompat.getColor(context, android.R.color.white),
        darkColor: Int = ContextCompat.getColor(context, android.R.color.black)
    ) {
        this.lightColor = lightColor
        this.darkColor = darkColor
    }

    fun setTitleBarColor(@ColorRes resId: Int): TitleBar {
        binding.linear.setBackgroundResource(resId)
        val brightness = ContextCompat.getColor(context, resId).brightness()
        currColor = if (!brightness) lightColor else darkColor
        binding.titleView.setTextColor(currColor)
        binding.tvRight.setTextColor(currColor)

        binding.layoutBack.addColorMask(currColor)
        binding.ivRightLayout.addRippleEffect(currColor)
        binding.titleLl.addRippleEffect(currColor)

        binding.backView.setColorFilter(currColor)
        binding.titleImg.setColorFilter(currColor)
        binding.ivRight.setColorFilter(currColor)
        getCurrentActivity()?.setLightStatusBars(brightness)
        return this
    }

    /**
     * 不显示整个titleBar
     */
    fun setTitleNoBar(): TitleBar {
        binding.linear.getSystemWindow { systemWindow ->
            //为需要偏移的view设置padding
            binding.linear.setPadding(0, systemWindow.top, 0, 0)
            binding.linear.setLayoutParams(
                LinearLayoutCompat.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    systemWindow.top
                )
            )
        }
        return this
    }

    fun setTitleImg(@DrawableRes resId: Int): TitleBar {
        binding.titleImg.visibility = visibility
        binding.titleImg.setImageResource(resId)
        binding.titleImg.setColorFilter(currColor)
        return this
    }

    fun setRightImgTv(
        @DrawableRes resId: Int? = null,
        text: String? = null,
        onClick: (() -> Unit)? = null
    ): TitleBar {
        binding.ivRightLayout.visibility = visibility
        onClick?.let {
            binding.ivRightLayout.addRippleEffect(currColor)
            binding.ivRightLayout.setOnClickListener { onClick.invoke() }
        }
        resId?.let {
            binding.ivRight.visibility = visibility
            binding.ivRight.setImageResource(it)
            binding.ivRight.setColorFilter(currColor)
        }
        text?.let {
            binding.tvRight.visibility = visibility
            binding.tvRight.text = text
            binding.tvRight.setTextColor(currColor)
        }

        return this
    }

    fun setOnTitleClick(click: OnClickListener): TitleBar {
        binding.titleLl.addRippleEffect(currColor)
        binding.titleLl.setOnClickListener(click)
        return this
    }

    fun setLeftImg(b: Boolean): TitleBar {
        binding.backView.visibility = if (b) VISIBLE else GONE
        return this
    }

}
